from BeautifulSoup import BeautifulSoup

def cleanTagSoup(HTMLtext):
    """A Simple BeautifulSoup recipe to extract all tags from an XML text"""
    return ''.join(BeautifulSoup(HTMLtext).findAll(text=True))

def find_first_occurance_excerpt(plainText, pattern, length = 100):
    """"quick and dirty way of finding the first occurance of pattern and highlight it """
    try:
        # we are doing case insensitive matching here
        index = plainText.lower().index(pattern.lower())
        start = index - length/2 if index > length/2 else 0
        end = start + length
        return "".join([plainText[start:index], ''.join(['<b style="color:black;">', pattern, '</b>']),  plainText[index + len(pattern):end], "..."])
    except ValueError:
        return ""
    
    

def test_main():
    return find_first_occurance_excerpt("I run into a fox which is a totally another ####################################################fox of fox", 'fox', 40)


if __name__ == "__main__":
    print test_main()